
const {
  getPost, getUserById, isLikePost, disLikePost, likePost, comment, reply, delReview, getPostReview, likeReview, disLikeReview, isLikeReview,isfollow
} = require('../../apis/api')


import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'



Page({

  /**
   * 页面的初始数据
   */
  data: {
    //用户信息
    id: "",
    avatarUrl: "",
    name: "",
    typeList: ["摄影", "学习", "美食", "旅游", "穿搭"],
    current: 0,
    imgUrls: [],
    nid: "",
    video_urls: [],
    post_title: "",
    content: "",
    type: "摄影",
    time: "09-29",
    love: false,
    loveNum: "100",
    commentNum: "100",
    comment: "",
    comment2:"",
    currentComment:"",
    indicatorDots: true, //小点
    indicatorColor: "white",//指示点颜色
    activeColor: "coral",//当前选中的指示点颜色
    autoplay: false, //是否自动轮播
    interval: 3000, //间隔时间
    duration: 3000, //滑动时间
    show: false,
    show2: false,
    show3: false,
    showType: "pic",
    appraiseList: [],
    index1:'',
    index2:'',
    relation:false
  },
  comment: function (e) {
    console.log(e.currentTarget.dataset)
    this.setData({
      show: true,
      currentComment:e.currentTarget.dataset.reviewid,
      index1:e.currentTarget.dataset.curindex,
      index2:e.currentTarget.dataset.curindexs
    })
  },
  onComment(){
    var replied
    if(this.data.comment2){
      console.log(this.data.appraiseList[this.data.index1])
      if(this.data.index2){
        replied="回复了'"+this.data.appraiseList[this.data.index1].reply_list[this.data.index2].content+"':";
      }else{
        replied="";
      }
     
      

      reply(this.data.token,this.data.currentComment,this.data.nid,replied+this.data.comment2,(res)=>{
        if(res.data.code===200){
          wx.showToast({
            title: '发送成功',
            icon:'success'
          })
          this.setData({
            comment2: ""
          })
          this.onReady()
        }else{
          wx.showToast({
            title: res.data.message,
            icon:'none'
          })
        }
      })
    }else{
      wx.showToast({
        title: '不可发送空消息',
        icon:'none'
      })
    }
    
  },
  send() {
    if(this.data.comment){
      comment(this.data.token, this.data.nid, this.data.comment, (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '发送成功',
            icon: 'success'
          })
          this.setData({
            comment: ""
          })
          this.onReady()
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          });
        }
      })
    }else{
      wx.showToast({
        title: '不可发送空消息',
        icon:'none'
      })
    }
  },
  longPress(e) {
    this.setData({
      show2: true,
      currentComment:e.currentTarget.dataset.reviewid
    })
  },
  onClose2() {
    this.setData({ show2: false })
  },
  delete() {
    delReview(this.data.token,this.data.currentComment,(res)=>{
      if(res.data.code===200){
        wx.showToast({
          title: '删除成功',
          icon:'success'
        })
        this.setData({
          show2:false
        })
        this.onReady()
      }else{
        wx.showToast({
          title: res.data.message,
          icon: 'none',
        });
        this.setData({
          show2:false
        })
      }
    })
  },
  // 点击展开
  chooseUnfold: function (e) {
    var key = e.currentTarget.dataset.key;
    var val = e.currentTarget.dataset.value;
    key = key + '.isOpen';
    this.setData({
      [key]: !val
    })
  },
  // 点赞功能逻辑s
  praiseThiss: function (e) {
    var index = e.currentTarget.dataset.curindex;
    console.log("index1",index)
    if (this.data.appraiseList[index]) {
      var change = this.data.appraiseList[index].change;
      if (change !== undefined) {
        var num = this.data.appraiseList[index].likes;
        if (change) {
          this.data.appraiseList[index].likes = (num - 1);
          this.data.appraiseList[index].change = false;

          disLikeReview(this.data.token,e.currentTarget.dataset.reviewid,(res)=>{
            if(res.data.code===200){
              wx.showToast({
                title: '取消成功',
                icon:'success'
              })
            }else{
              wx.showToast({
                title: res.data.message,
                icon:'none'
              })
            }
          })

         
        } else {

          
          this.data.appraiseList[index].likes = (num + 1);
          this.data.appraiseList[index].change = true;

          likeReview(this.data.token,e.currentTarget.dataset.reviewid,(res)=>{
            if(res.data.code===200){
              wx.showToast({
                title: '点赞成功',
                icon:'success'
              })
            }else{
              wx.showToast({
                title: res.data.message,
                icon:'none'
              })
            }
          })
      
        }
        this.setData({
          appraiseList: this.data.appraiseList
        })
      }
    }
  },
  // 点赞内层逻辑
  praiseThisss: function (e) {
    var index = e.currentTarget.dataset.curindex;
    var indexs = e.currentTarget.dataset.curindexs;

    if (this.data.appraiseList[index].reply_list[indexs]) {
      
      var change = this.data.appraiseList[index].reply_list[indexs].change;
   
      if (change !== undefined) {
        
        var num = this.data.appraiseList[index].reply_list[indexs].likes;
        if (change) {
          disLikeReview(this.data.token,e.currentTarget.dataset.reviewid,(res)=>{
            if(res.data.code===200){
              wx.showToast({
                title: '取消成功',
                icon:'success'
              })
            }else{
              wx.showToast({
                title: res.data.message,
                icon:'none'
              })
            }
          })
      
          this.data.appraiseList[index].reply_list[indexs].likes = (num - 1);
          this.data.appraiseList[index].reply_list[indexs].change = false;
        } else {
          likeReview(this.data.token,e.currentTarget.dataset.reviewid,(res)=>{
            if(res.data.code===200){
              wx.showToast({
                title: '点赞成功',
                icon:'success'
              })
            }else{
              wx.showToast({
                title: res.data.message,
                icon:'none'
              })
            }
          })
      
          this.data.appraiseList[index].reply_list[indexs].likes = (num + 1);
          this.data.appraiseList[index].reply_list[indexs].change = true;
        }
        this.setData({
          appraiseList: this.data.appraiseList
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      nid: options.nid
    })
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['username', 'userAvatar', 'email', 'token'],
      actions: ['setUsername', 'setUserAvatar', 'setEmail', 'setToken'],
    })
  },
  changeLike() {
    console.log("love", this.data.love)
    if (this.data.love === 'true') {
      disLikePost(this.data.token, this.data.nid, (res) => {
        if (res.data.code === 200) {
          this.setData({
            love: 'false',
            loveNum: this.data.loveNum - 1
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          });
        }
      })
    } else {
      likePost(this.data.token, this.data.nid, (res) => {
        if (res.data.code === 200) {
          this.setData({
            love: 'true',
            loveNum: this.data.loveNum + 1
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          });
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(options) {
    var that = this
    wx.showLoading({  // 显示加载中loading效果 
      title: "加载中",
      mask: true  //开启蒙版遮罩
    });
    isLikePost(this.data.token, this.data.nid, (res) => {
      if (res.data.code === 200) {
        this.setData({
          love: res.data.data==='true'?true:false
        })
      }
    });


    // 定义一个获取 post 的函数，返回一个 Promise
    function getPostAsync(token, nid) {
      return new Promise((resolve, reject) => {
        getPost(token, nid, (res) => {
          if (res.data.code === 200) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message));
          }
        });
      });
    }

    // 定义一个获取用户信息的函数，返回一个 Promise
    function getUserByIdAsync(token, id) {
      return new Promise((resolve, reject) => {
        getUserById(token, id, (res) => {
          if (res.data.code === 200) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message));
          }
        });
      });
    }

    // 使用 Promise 进行异步操作
    getPostAsync(this.data.token, this.data.nid)
      .then((postData) => {
        if (postData.pictures_urls.length !== 0) {
          return {
            id: postData.post_owner_id,
            imgUrls: postData.pictures_urls,
            type: postData.type,
            time: postData.post_date,
            loveNum: postData.likes,
            post_title: postData.post_title,
            content: postData.content,
            showType: 'pic'
          };
        } else {
          return {
            id: postData.post_owner_id,
            video_urls: postData.video_urls,
            type: postData.type,
            time: postData.post_date,
            loveNum: postData.likes,
            post_title: postData.post_title,
            content: postData.content,
            showType: 'video'
          };
        }
      })
      .then((postInfo) => {
        return getUserByIdAsync(this.data.token, postInfo.id)
          .then((userData) => {
            postInfo.name = userData.userName;
            postInfo.avatarUrl = userData.pictureUrl;
            return postInfo;
          });
      })
      .then((finalData) => {
        this.setData(finalData);
        isfollow(this.data.token,this.data.id,(res)=>{
          if(res.data.code===200){
            this.setData({
              relation:res.data.data==='true'?true:false
            })
            wx.hideLoading()
          }
        })
      })
      .catch((error) => {
        console.error(error);
        wx.showToast({
          title: error.message,
          icon: 'none',
        });
      });

      this.showComment()
  },
   
  showComment(){
    function transformData(data, token) {
      const appraiseList = data.map(async item => {
        const firstReview = item.firstReview;
        const reply_list = await Promise.all(item.secondReviews.map(async secondReview => {
          const changePromise = new Promise((resolve, reject) => {
            isLikeReview(token, secondReview.reviewId, (res) => {
              if (res.data.code === 200) {
                resolve(res.data.data);
              } else {
                reject(new Error(res.data.message));
              }
            });
          });
    
          const userPromise = new Promise((resolve, reject) => {
            getUserById(token, secondReview.authorId, (res) => {
              if (res.data.code === 200) {
                resolve({
                  username: res.data.data.userName,
                  img: res.data.data.pictureUrl,
                });
              } else {
                reject(new Error(res.data.message));
              }
            });
          });
    
          const [change, userInfo] = await Promise.all([changePromise, userPromise]);
    
          return {
            isOpen: false,
            authorId: secondReview.authorId,
            postId: secondReview.postId,
            repliedReviewId: secondReview.repliedReviewId,
            isPostOwnerCheck: secondReview.isPostOwnerCheck,
            likes: secondReview.likes,
            content: secondReview.content,
            reviewDate: secondReview.reviewDate,
            reviewId: secondReview.reviewId,
            change: change === 'true' ? true : false,
            username: userInfo.username,
            img: userInfo.img,
          };
        }));
    
        const changePromise = new Promise((resolve, reject) => {
          isLikeReview(token, firstReview.reviewId, (res) => {
            if (res.data.code === 200) {
              resolve(res.data.data);
            } else {
              reject(new Error(res.data.message));
            }
          });
        });
    
        const userPromise = new Promise((resolve, reject) => {
          getUserById(token, firstReview.authorId, (res) => {
            if (res.data.code === 200) {
              resolve({
                username: res.data.data.userName,
                img: res.data.data.pictureUrl,
              });
            } else {
              reject(new Error(res.data.message));
            }
          });
        });
    
        const [change, userInfo] = await Promise.all([changePromise, userPromise]);
    
        return {
          isOpen: false,
          change: change === 'true' ? true : false,
          authorId: firstReview.authorId,
          username: userInfo.username,
          img: userInfo.img,
          postId: firstReview.postId,
          repliedReviewId: firstReview.repliedReviewId,
          isPostOwnerCheck: firstReview.isPostOwnerCheck,
          likes: firstReview.likes,
          content: firstReview.content,
          reviewDate: firstReview.reviewDate,
          reviewId: firstReview.reviewId,
          reply_list: reply_list,
        };
      });
    
      return Promise.all(appraiseList);
    }
    

    // getPostReview(this.data.token,this.data.nid,(res)=>{
    //   if(res.data.code===200){
    //     const arr = transformData(res.data.data)
    //     console.log("转换之后",arr)
    //     this.setData({
    //       appraiseList:arr
    //     })
    //   }
    // })

    getPostReview(this.data.token, this.data.nid, async (res) => {
      if (res.data.code === 200) {
        try {
          const arr = await transformData(res.data.data, this.data.token);
          console.log("转换之后", arr);
          this.setData({
            appraiseList: arr,
          });
        } catch (error) {
          console.error(error);
          wx.showToast({
            title: error.message,
            icon: 'none',
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})